<template>
  <div id="addUserPage">
    <h2 style="margin-bottom: 32px" v-if="!props.id">创建用户</h2>
    <h2 style="margin-bottom: 32px" v-else>编辑用户</h2>
    <el-form
      :model="form"
      :style="{ width: '480px', margin: '0 auto' }"
      label-align="left"
      auto-label-width
    >
      <el-form-item field="userAccount" label="用户账号">
        <el-input v-model="form.userAccount" placeholder="请输入用户账号" />
      </el-form-item>
      <el-form-item field="userPassword" label="用户密码">
        <el-input v-model="form.userPassword" placeholder="请输入用户密码" />
      </el-form-item>
      <el-form-item field="movieName" label="用户名称">
        <el-input v-model="form.userName" placeholder="请输入用户名称" />
      </el-form-item>
      <el-form-item field="userRole" label="用户角色">
        <el-select v-model="form.userRole" placeholder="请输入用户角色">
          <el-option
            v-for="value of USER_ROLE_MAP"
            :key="value"
            :value="value"
            :label="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" style="width: 120px"
          >提交
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watchEffect } from "vue";
import API from "@/api";
import { useLoginUserStore } from "@/store/userStore";
import { useRouter } from "vue-router";
import { withDefaults, defineProps } from "vue";

import { ElMessage } from "element-plus";
import { MOVIE_TYPE_MAP, USER_ROLE_MAP } from "@/constant/movie";
import {
  addUserUsingPost,
  getUserByIdUsingGet,
  getUserVoByIdUsingGet,
  updateUserUsingPost,
} from "@/api/userController";

const loginUserStore = useLoginUserStore();
const router = useRouter();

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});

const old = ref<API.UserVO>();

const form = ref({
  userName: "",
  userAvatar: "",
} as API.UserQueryRequest);

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.id) {
    return;
  }
  const res = await getUserByIdUsingGet({
    id: props.id as any,
  });
  if (res.data.code === 0 && res.data.data) {
    old.value = res.data.data as any;
    form.value = res.data.data;
  } else {
    ElMessage({
      message: "获取数据失败，" + res.data.message,
      type: "error",
    });
  }
};

watchEffect(() => {
  loadData();
});

const handleSubmit = async () => {
  let res: any;
  //判断是否是更新操作
  if (props.id) {
    res = await updateUserUsingPost({
      id: props.id as any,
      ...form.value,
    });
  } else {
    res = await addUserUsingPost(form.value);
  }

  if (res.data.code === 0) {
    ElMessage({
      message: "操作成功",
      type: "success",
    });
    setTimeout(() => {
      router.push(`/`);
    }, 3000);
  } else {
    ElMessage({
      message: "操作失败，" + res.data.message,
      type: "error",
    });
  }
};
</script>
